// 直接更新state的多个方法的对象
import Vue from 'vue'
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORYS,
  RECEIVE_SHOPLIST,
  RECEIVE_USERINFO,
  RESET_USERINFO,
  RECEIVE_GOODS,
  RECEIVE_RATINGS,
  RECEIVE_INFO,
  INCREMENT_FOOD_COUNT,
  DECREMENT_FOOD_COUNT,
  CLEAR_CART,
  RECEIVE_SEARCH_SHOPS
} from './mutation-types'

export default {
  [RECEIVE_ADDRESS] (state, {address}) {
    state.address = address
  },

  [RECEIVE_CATEGORYS] (state, {categorys}) {
    state.categorys = categorys
  },

  [RECEIVE_SHOPLIST] (state, {shopList}) {
    state.shopList = shopList
  },

  [RECEIVE_USERINFO] (state, {userInfo}) {
    state.userInfo = userInfo
  },

  [RESET_USERINFO] (state) {
    state.userInfo = {}
  },

  [RECEIVE_GOODS] (state, {goods}) {
    state.goods = goods
  },

  [RECEIVE_RATINGS] (state, {ratings}) {
    state.ratings = ratings
  },

  [RECEIVE_INFO] (state, {info}) {
    state.info = info
  },

  [INCREMENT_FOOD_COUNT] (state, {food}) {
    if (!food.count) { // 初始值，值不存在的时候，第一次增加为1
      // food.count = 1 新增属性（没有数据绑定）则调用Vue.set
      // Vue.set （对象 属性名 属性值）
      Vue.set(food, 'count', 1) // count是个字符串 不加‘’就是变量了,'count'让新增属性也有数据绑定
      state.cartFoods.push(food) // 将food添加到cartFoods中
    } else {
      food.count++
    }
  },

  [DECREMENT_FOOD_COUNT] (state, {food}) { // food是接受的参数
    if (food.count) { // 只有有值的时候才去减
      food.count--
      if (food.count === 0) {
        // 将food从cartFoods中移除 删除找到food的下标并删除一个
        state.cartFoods.splice(state.cartFoods.indexOf(food), 1)
      }
    }
  },

  [CLEAR_CART] (state) {
    // 清除food中的count,循环出food中的food.count，并清零
    // 简单写法 state.cartFoods.forEach(food => food.count = 0 ）
    state.cartFoods.forEach((food) => { // 循环food并找出他中的food.count
      food.count = 0
    })
    // 移除购物车中所有购物项
    state.cartFoods = []
  },

  [RECEIVE_SEARCH_SHOPS] (state, {searchShops}) { // 搜索的操作
    state.searchShops = searchShops
  }

}
